package com.lemon.core.common.web.response;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc: ResponseUtils
 * @author: 柠檬的柠丶
 * @createTime: 2017年10月15日 下午2:53:36
 * @history:
 * @version: v1.0
 */
public class ResponseUtils {
	
	/**
     * 标识
     */
    private static final String FLAG = "flag";
    
    /**
	 * 数据
	 */
	private static final String DATA = "data";
	
	/**
	 * 返回信息
	 */
	private static final String MSG = "msg";
	
	/**
	 * msg 为空
	 */
	private static final String EMPTY_MSG = "";
	
	/**
	 * data 为空
	 */
	private static final String EMPTY_DATA = "";
	
	
	public static void success(HttpServletResponse response) {
		result(response, true, EMPTY_DATA, EMPTY_MSG);
	}
	
	public static void success(HttpServletResponse response, Object data) {
		result(response, true, data, EMPTY_MSG);
	}
	
	/*public static void success(HttpServletResponse response, String msg) {
		result(response, true, EMPTY_DATA, msg);
	}*/
	
	/**
	* 成功信息返回
	* @author: lottery
	* @createTime: 2017年10月15日 下午3:25:48
	* @param response
	* @param data
	* @param msg void
	 */
	public static void success(HttpServletResponse response, Object data, String msg) {
		result(response, true, data, msg);
	}
	
	public static void error(HttpServletResponse response) {
		result(response, false, EMPTY_DATA, EMPTY_MSG);
	}
	
	public static void error(HttpServletResponse response, Object data) {
		result(response, false, data, EMPTY_MSG);
	}
	
	/*public static void error(HttpServletResponse response, String msg) {
		result(response, false, EMPTY_DATA, EMPTY_MSG);
	}*/
	
	/**
	* 错误信息返回
	* @author: lottery
	* @createTime: 2017年10月15日 下午3:25:36
	* @param response
	* @param data
	* @param msg void
	 */
	public static void error(HttpServletResponse response, Object data, String msg) {
		result(response, false, data, msg);
	}
	
	/**
	* 向界面返回数据
	* @author: lottery
	* @createTime: 2017年10月15日 下午3:00:46
	* @param response	返回数据
	* @param flag		操作是否成功
	* @param data		信息描述
	* @param msg void
	 */
	private static void result(HttpServletResponse response, boolean flag, Object data, String msg) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(FLAG, flag);
		map.put(DATA, data);
		map.put(MSG, msg);
		String listJson = JSONObject.toJSONString(map, SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty,
				SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.DisableCircularReferenceDetect);
		WebUtils.sendDirectToClient(response, WebUtils.APPLICATIONTYPE_JSON,
				WebUtils.CONTENT_CHARSET_UTF8, listJson);
	}
}
